package string.understanding;

/**
 * @Classname : BasicCalculatorIII
 * @Description : 772. 基本计算器 III
 * https://leetcode.cn/problems/basic-calculator-iii/
 * @Author : chentianyu
 * @Date 2022/12/20 22:22
 */


public class BasicCalculatorIII {
    public int calculate(String s) {
        return cal(s, 0)[0];
    }

    private int[] cal(String s, int pos) {
        char op = '+';
        int left = 0, right = 0;
        for (; pos < s.length(); pos++) {
            int[] parse;
            // 遇到左括号就递归计算括号内表达式
            if (s.charAt(pos) == '(') parse = cal(s, pos + 1);
            else parse = getNum(s, pos);
            int num = parse[0];
            pos = parse[1];

            switch (op) {
                case '+' : left += right; right = num; break;
                case '-' : left += right; right = -num; break;
                case '*' : right *= num; break;
                case '/' : right /= num; break;
            }
            // 遇到右括号说明括号内部计算结束，返回上层方法
            if (pos < s.length() && s.charAt(pos) == ')') return new int[]{left + right, pos + 1};
            if (pos < s.length()) op = s.charAt(pos);
        }
        return new int[]{left + right, s.length()};
    }

    private int[] getNum(String s, int pos) {
        int num = 0;
        while (pos < s.length() && s.charAt(pos) >= '0' && s.charAt(pos) <= '9') {
            num = num * 10 + s.charAt(pos++) - '0';
        }
        return new int[]{num, pos};
    }
}
